package com.team.mp.api.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.team.mp.api.service.intf.LabelService;
import com.team.mp.constants.RedisKey;
import com.team.mp.mapper.dao.LabelDao;
import com.team.mp.mapper.dao.SysUserDao;
import com.team.mp.mapper.entity.Label;
import com.team.mp.mapper.entity.SysUser;
import com.team.mp.vo.R;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LabelServiceImpl implements LabelService {
    @Resource
    private LabelDao dao;
    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private StringRedisTemplate template;

    @Override
    public R save(String name,String token) {
        if (name != null) {
            Label label = new Label();
            String id = template.opsForValue().get(RedisKey.AUTH_TOKEN + token);
            SysUser sysUser = sysUserDao.selectById(id);
            label.init(sysUser.getUsername());
            if (dao.insert(label) > 0) {
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R update(String name,Integer id) {
        if (name != null) {
            if (dao.updateLabName(name, id) > 0) {
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R updateStatus(Integer id) {
        Label label = dao.selectById(id);
        if (label.getStatus() == 1) {
            if (dao.updateLabStatus0(id) > 0){
                return R.ok();
            }
        }else {
            if (dao.updateLabStatus1(id) > 0) {
                return R.ok();
            }
        }
        return R.fail();
    }


    @Override
    public R del(long id) {
        if(id>0){
            int i=dao.deleteById(id);
            if(i>0){
                return R.ok();
            }
        }
        return R.fail("删除异常");
    }

    @Override
    public R queryAll() {
        return R.ok(dao.selectList(null));
    }

    @Override
    public R queryPage(String name, int page, int size) {
        QueryWrapper<Label> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        return R.ok(dao.selectPage(new Page<>(page,size),queryWrapper));
    }
}
